﻿using cn.jpush.api;
using cn.jpush.api.push.mode;
using KD.Service.HR.Utility;
using Logistics.Model;
using Logistics.Model.Response;
using Logistics.Service;
using Logistics.Utility;
using Logistics.WebApi.Attributes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http;

namespace Logistics.WebApi.Controllers
{
    [MyAuthority]
    public class BidPriceController:ApiController
    {
        private BidWLPriceService priceService = new BidWLPriceService();
        private AndroidTokenService androidService = new AndroidTokenService();
        private BidLoadService service = new BidLoadService();
        private CompushBaseService compushService = new CompushBaseService();
        private BidBaseService bidbase = new BidBaseService();

        /// <summary>
        /// 获取第一次物流企业报价列表
        /// </summary>
        /// <param name="bid_id"></param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetPriceList(int bid_id)
        {
            var responseModel = new ResponseModel();
            try
            {
                responseModel.mod=priceService.GetPriceList(bid_id);
                responseModel.InitResultState(GetDataStateEnum.Success);
            }
            catch (Exception ex)
            {
                responseModel.InitResultState(ex);
            }
            return responseModel;
        }

        /// <summary>
        /// 获取重新选标列表
        /// </summary>
        /// <param name="bid_id"></param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetRePriceList(int bid_id)
        {
            var responseModel = new ResponseModel();
            try
            {
                responseModel.mod = priceService.GetRePriceList(bid_id);
               
                responseModel.InitResultState(GetDataStateEnum.Success);
            }
            catch (Exception ex)
            {
                responseModel.InitResultState(ex);
            }
            return responseModel;
        }

        /// <summary>
        /// 第一次选标操作
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel ChoiceBidPrice(wuliu_bid_wlcompany_query price)
        {
            var accountId = Convert.ToInt32(HttpContext.Current.Request.Headers[LogisticsConst.LOGIN_HEADER]);
            var responseModel = new ResponseModel(); 
            try
            {
                var bidmod = bidbase.GetBid((int)price.bid_id);
                var pricemod = priceService.GetPriceBid(price.bid_wl_id);
                var newLoad = new wuliu_bid_load();
                newLoad.load_no = NoBuilder.GetLoadNo();
                newLoad.load_remark = "";
                newLoad.load_state = "1";//
                newLoad.load_time = DateTime.Now;
                newLoad.Operator = accountId.ToString();
                newLoad.order_num = bidmod.number;
                newLoad.price = pricemod.final_price;
                newLoad.receipt_time = (int)bidmod.receipt_time;
                newLoad.start_address = bidmod.start_address;
                newLoad.start_bid_time = (int)bidmod.start_bid_time;
                newLoad.start_city_id = bidmod.start_city_id;
                newLoad.start_city_name = bidmod.start_city_name;
                newLoad.wuliu_id = pricemod.wuliu_id;
                newLoad.wuliu_name = pricemod.wuliu_name;
                newLoad.wuliu_no = pricemod.wuliu_no;
                newLoad.wuliu_bid_state = "10";
                newLoad.bid_flag = "1";
                newLoad.bid_id = bidmod.bid_id;
                newLoad.bid_no = bidmod.bid_no;
                newLoad.tax = pricemod.tax;
                newLoad.tax_price = pricemod.tax_price;
                newLoad.bid_state = 1;//
                newLoad.company_name = bidmod.company_name;
                newLoad.company_no = bidmod.company_no;
                newLoad.consignee_time = (int)bidmod.consignee_time;
                newLoad.end_address = bidmod.end_address;
                newLoad.end_address2 = bidmod.end_address2;
                newLoad.end_bid_time = (int)bidmod.end_bid_time;
                newLoad.end_city_id = bidmod.end_city_id;
                newLoad.end_city_id2 = bidmod.end_city_id2;
                newLoad.end_city_name = bidmod.end_city_name;
                newLoad.end_city_name2 = bidmod.end_city_name2;
                var en = priceService.ChoiceBidPirce((int)price.bid_id, price.bid_wl_id, pricemod, newLoad);
                responseModel.mod = en;
                if (en)
                {
                    #region 手机推送

                    string title="", content="",registrationid="";

                  
                    var list = androidService.GetAndroidToken((int)pricemod.wuliu_id);

                    foreach(var mod in list)
                    {
                        try
                        {

                            content = bidmod.bid_no + "&&5&&尊敬的企运宝用户，恭喜您，您参与订单号为" + bidmod.bid_no + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";

                            wuliu_compush_base compushmod = new wuliu_compush_base();
                            compushmod.account_id = mod.account_id;
                            compushmod.bid_id = bidmod.bid_id;
                            //string pushcontent = bidmod.bid_no + "&&" + bidmod.state + "&&请" + pick.ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmod.content = content;
                            compushmod.state = 1;
                            compushmod.type = 10;
                            compushmod.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmod.push_time = DateConvert.DateTimeToStamp(DateTime.Now.AddMinutes(1));//推送时间需要计算保存

                            var pushid = compushService.AddCompushBase(compushmod);

                            wuliu_compush_base_momory compushbase = new wuliu_compush_base_momory();
                            compushbase.push_id = pushid;
                            compushbase.account_id = mod.account_id;
                            compushbase.state = 1;
                            compushbase.type = 10;
                            compushbase.content = content;
                            var momoryid = compushService.AddCompushBaseMomory(compushbase);



                            registrationid = mod.android_token;
                            //PushAndroid(title, content, bidmod.bid_no, registrationid);//激光推送



                            //Thread.Sleep(1000);
                            wuliu_compush_base compushmods = new wuliu_compush_base();
                            compushmods.account_id = mod.account_id;
                            compushmods.bid_id = bidmod.bid_id;
                            string pushcontent = bidmod.bid_no + "&&5&&请" + DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmods.content = pushcontent;
                            compushmods.state = 1;
                            compushmods.type = 10;
                            compushmods.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmods.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存

                            var pushids = compushService.AddCompushBase(compushmods);

                            wuliu_compush_base_momory compushbases = new wuliu_compush_base_momory();
                            compushbases.push_id = pushids;
                            compushbases.account_id = mod.account_id;
                            compushbases.state = 1;
                            compushbases.type = 10;
                            compushbases.content = pushcontent;
                            var momoryids = compushService.AddCompushBaseMomory(compushbases);

                            wuliu_compush_base compushmod2 = new wuliu_compush_base();
                            compushmod2.account_id = mod.account_id;
                            compushmod2.bid_id = bidmod.bid_id;
                            string pushcontent2 = bidmod.bid_no + "&&5&&请" + DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间半小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmod2.content = pushcontent2;
                            compushmod2.state = 1;
                            compushmod2.type = 10;
                            compushmod2.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmod2.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-0.5));//推送时间需要计算保存
                            var pushid2 = compushService.AddCompushBase(compushmod2);

                            wuliu_compush_base_momory compushbase2 = new wuliu_compush_base_momory();
                            compushbase2.push_id = pushid2;
                            compushbase2.account_id = mod.account_id;
                            compushbase2.state = 1;
                            compushbase2.type = 10;
                            compushbase2.content = pushcontent;
                            var momoryid2 = compushService.AddCompushBaseMomory(compushbase2);
                        }
                        catch (Exception ex)
                        {

                        }
                    }

                    var IOSlist = androidService.GetIOSToken((int)pricemod.wuliu_id);

                    foreach (var mod in IOSlist)
                    {
                        try
                        {
                            content = bidmod.bid_no + "&&5&&尊敬的企运宝用户，恭喜您，您参与订单号为" + bidmod.bid_no + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";

                            wuliu_compush_base compushmod = new wuliu_compush_base();
                            compushmod.account_id = mod.account_id;
                            compushmod.bid_id = bidmod.bid_id;
                            //string pushcontent = bidmod.bid_no + "&&" + bidmod.state + "&&请" + pick.ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmod.content = content;
                            compushmod.state = 1;
                            compushmod.type = 10;
                            compushmod.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmod.push_time = DateConvert.DateTimeToStamp(DateTime.Now.AddMinutes(1));//推送时间需要计算保存

                            var pushid = compushService.AddCompushBase(compushmod);

                            wuliu_compush_base_momory compushbase = new wuliu_compush_base_momory();
                            compushbase.push_id = pushid;
                            compushbase.account_id = mod.account_id;
                            compushbase.state = 1;
                            compushbase.type = 10;
                            compushbase.content = content;
                            var momoryid = compushService.AddCompushBaseMomory(compushbase);



                            registrationid = mod.ios_token;
                            //PushAndroid(title, content, bidmod.bid_no, registrationid);//激光推送

                            //Thread.Sleep(1000);
                            wuliu_compush_base compushmods = new wuliu_compush_base();
                            compushmods.account_id = mod.account_id;
                            compushmods.bid_id = bidmod.bid_id;
                            string pushcontent = bidmod.bid_no + "&&5&&请" + DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间1小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmods.content = pushcontent;
                            compushmods.state = 1;
                            compushmods.type = 10;
                            compushmods.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmods.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-1));//推送时间需要计算保存

                            var pushids = compushService.AddCompushBase(compushmods);

                            wuliu_compush_base_momory compushbases = new wuliu_compush_base_momory();
                            compushbases.push_id = pushids;
                            compushbases.account_id = mod.account_id;
                            compushbases.state = 1;
                            compushbases.type = 10;
                            compushbases.content = pushcontent;
                            var momoryids = compushService.AddCompushBaseMomory(compushbases);

                            wuliu_compush_base compushmod2 = new wuliu_compush_base();
                            compushmod2.account_id = mod.account_id;
                            compushmod2.bid_id = bidmod.bid_id;
                            string pushcontent2 = bidmod.bid_no + "&&5&&请" + DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).ToString("hh:mm:00") + "到" + bidmod.end_city_name + "的" + bidmod.company_name + "取货，剩余取货时间半小时，订单号" + bidmod.bid_no + "，请尽快安排出车，祝您一帆风顺。";
                            compushmod2.content = pushcontent2;
                            compushmod2.state = 1;
                            compushmod2.type = 10;
                            compushmod2.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            compushmod2.push_time = DateConvert.DateTimeToStamp(DateConvert.StampToDateTime(bidmod.consignee_time.ToString()).AddHours(-0.5));//推送时间需要计算保存
                            var pushid2 = compushService.AddCompushBase(compushmod2);

                            wuliu_compush_base_momory compushbase2 = new wuliu_compush_base_momory();
                            compushbase2.push_id = pushid2;
                            compushbase2.account_id = mod.account_id;
                            compushbase2.state = 1;
                            compushbase2.type = 10;
                            compushbase2.content = pushcontent;
                            var momoryid2 = compushService.AddCompushBaseMomory(compushbase2);
                        }
                        catch (Exception ex)
                        {

                        }


                    }

                    #endregion
                }
                responseModel.InitResultState(StateEnum.Success);
            }
            catch (Exception ex)
            {
                responseModel.InitResultState(ex);
            }
            return responseModel;
        }

        public static void PushAndroid(string title, string content,string bidno, string RegistrationID = "")
        {
            string ApiKey = "cc5c60669b05b76744a1f112";
            string APIMasterSecret = "64b111e5d59fc0c10a76a5d6";
            try
            {
                Random ran = new Random(); int sendno = ran.Next(1, 2100000000);//随机生成的一个编号   
                string app_key = ApiKey;
                string masterSecret = APIMasterSecret;
                int receiver_type = 5;
                //接收者类型。2、指定的 tag。3、指定的 alias。4、广播：对 app_key 下的所有用户推送消息。5、根据 RegistrationID 进行推送。当前只是 Android SDK r1.6.0 版本支持   
                string receiver_value = RegistrationID;
                int msg_type = 1;//1、通知2、自定义消息（只有 Android 支持）    
                string msg_content = "{\"bid_no\":\"" + bidno + "\",\"flag\":\"4\",\"n_title\":\"" + title + "\",\"n_content\":\"" + content + "\"}";//消息内容 
                string platform = "android";//目标用户终端手机的平台类型，如： android, ios 多个请使用逗号分隔。               
                string verification_code = GetMD5Str(sendno.ToString(), receiver_type.ToString(), receiver_value, masterSecret);//验证串，用于校验发送的合法性。MD5       
                string postData = "sendno=" + sendno;
                postData += ("&app_key=" + app_key);
                postData += ("&masterSecret=" + masterSecret);
                postData += ("&receiver_type=" + receiver_type);
                postData += ("&receiver_value=" + receiver_value);
                postData += ("&msg_type=" + msg_type);
                postData += ("&msg_content=" + msg_content);
                postData += ("&platform=" + platform);
                postData += ("&verification_code=" + verification_code);
                //byte[] data = encoding.GetBytes(postData);    
                byte[] data = Encoding.UTF8.GetBytes(postData);
                string resCode = GetPostRequest(data);//调用极光的接口获取返回值      
                JpushMsg msg = Newtonsoft.Json.JsonConvert.DeserializeObject<JpushMsg>(resCode);//定义一个JpushMsg类，包含返回值信息，将返回的json格式字符串转成JpushMsg对象
            }
            catch (Exception ex) { }
        }
        /// <summary>       
        ///  /// MD5字符串      
        ///   /// </summary>       
        ///  /// <param name="paras">参数数组</param>      
        ///   /// <returns>MD5字符串</returns>      
        public static string GetMD5Str(params string[] paras)
        {
            string str = "";
            for (int i = 0; i < paras.Length; i++)
            {
                str += paras[i];
            }
            byte[] buffer = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str));
            string md5Str = string.Empty;
            for (int i = 0; i < buffer.Length; i++)
            {
                md5Str = md5Str + buffer[i].ToString("X2");
            }
            return md5Str;
        }


        /// <summary>        
        /// /// Post方式请求获取返回值 
        ///        /// </summary>    
        /// <param name="data"></param>      
        ///   /// <returns></returns>       
        public static string GetPostRequest(byte[] data)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://api.jpush.cn:8800/v2/push"); myRequest.Method = "POST";
            //极光http请求方式为post           
            myRequest.ContentType = "application/x-www-form-urlencoded";
            //按照极光的要求        
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();
            // Send the data.           
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // Get response           
            var response = (HttpWebResponse)myRequest.GetResponse();
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")))
            {
                string result = reader.ReadToEnd(); reader.Close(); response.Close(); return result;
            }
        }
        public class JpushMsg
        {
            private string sendno;//编号 
            public string Sendno { get { return sendno; } set { sendno = value; } }
            private string msg_id;//信息编号      
            public string Msg_id { get { return msg_id; } set { msg_id = value; } }
            private string errcode;//返回码 
            public string Errcode { get { return errcode; } set { errcode = value; } }
            private string errmsg;//错误信息   
            public string Errmsg { get { return errmsg; } set { errmsg = value; } }
        }

        /// <summary>
        /// 激光推送
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool PhonePush(string str)
        {
            string content = "尊敬的企运宝用户，恭喜您，您参与订单号为" + str + "的订单竞标成功！请尽快和发货方取得联系并安排出车，祝您一帆风顺。";
            JPushClient client = new JPushClient("85a8af5b452b225ad7eb6df7", "fc03a0cfc061493602d0eff5");
            PushPayload payload = PushObject_All_All_Alert(content);
            try
            {
                var result = client.SendPush(payload);
                //由于统计数据并非非是即时的,所以等待一小段时间再执行下面的获取结果方法
                System.Threading.Thread.Sleep(10000);
                /*如需查询上次推送结果执行下面的代码*/
                var apiResult = client.getReceivedApi(result.msg_id.ToString());
                var apiResultv3 = client.getReceivedApi_v3(result.msg_id.ToString());
                /*如需查询某个messageid的推送结果执行下面的代码*/
                var queryResultWithV2 = client.getReceivedApi("1739302794");
                var querResultWithV3 = client.getReceivedApi_v3("1739302794");
                return result.isResultOK();
            }
            catch (Exception e)
            {

            }
            return false;
        }

        public static PushPayload PushObject_All_All_Alert(string ALERT)
        {
            PushPayload pushPayload = new PushPayload();
            pushPayload.platform = Platform.all();
            pushPayload.audience = Audience.all();
            pushPayload.notification = new Notification().setAlert(ALERT);
            return pushPayload;
        }
      
    }
}